package com.wzdigit.wms.wms.controller.inv.count;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.gson.Gson;
import com.wzdigit.framework.Shift;
import com.wzdigit.framework.model.response.ErrorEntity;
import com.wzdigit.wms.basic.client.Pager;
import com.wzdigit.wms.basic.client.PagerInfo;
import com.wzdigit.wms.basic.client.response.Result;
import com.wzdigit.wms.basic.domain.asn.AsnHeader;
import com.wzdigit.wms.basic.domain.basic.Location;
import com.wzdigit.wms.basic.domain.basic.Sku;
import com.wzdigit.wms.basic.domain.basic.SkuCate;
import com.wzdigit.wms.basic.domain.basic.Zone;
import com.wzdigit.wms.basic.domain.inventory.Lotno;
import com.wzdigit.wms.basic.enums.inventory.count.header.InvIsDynamicEnum;
import com.wzdigit.wms.wms.client.request.inv.count.CountHeaderInsertDto;
import com.wzdigit.wms.wms.client.request.inv.count.CountHeaderRequest;
import com.wzdigit.wms.wms.client.request.inv.count.CountScopeDto;
import com.wzdigit.wms.wms.client.request.inv.count.CountScopeInfoDto;
import com.wzdigit.wms.wms.client.response.inv.count.CountHeaderResponse;
import com.wzdigit.wms.wms.constant.WmsWareConstant;
import com.wzdigit.wms.wms.domain.inv.count.InvCountHeader;
import com.wzdigit.wms.wms.domain.inv.count.InvCountScope;
import com.wzdigit.wms.wms.mapper.inv.count.InvCountHeaderMapper;
import com.wzdigit.wms.wms.service.inv.count.InvCountService;
import com.wzdigit.wms.wms.service.inv.count.InvCountTaskService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

/**
 *
 * 盘点BS
 * Created by zyf on 2021/10/11 21:26
 */
@RestController
@Api(tags = "盘点BS")
@RequestMapping(value = WmsWareConstant.API_VERSION)
public class InvCountController {
    public static final String REQUEST_MODEL = "/invCount";

    @Autowired
    private InvCountHeaderMapper invCountHeaderMapper;

    @Autowired
    private InvCountService invCountService;
    @Autowired
    private InvCountTaskService taskService;

    @ApiOperation(value = "获取盘点单主档（分页）", notes = "获取盘点单主档（分页）")
    @ApiResponses({@ApiResponse(code = 500, message = "系统出现异常", response = ErrorEntity.class)})
    @RequestMapping(value = REQUEST_MODEL + "/searchHeader", method = RequestMethod.GET)
    public PagerInfo<List<CountHeaderResponse>> searchCountHeader(
            CountHeaderRequest search, Pager<?> pager,
            HttpServletRequest servletRequest, HttpServletResponse servletResponse) {
        return invCountService.searchCountHeader(search,pager);
    }

    @ApiOperation(value = "导出盘点单主档", notes = "导出盘点单主档")
    @ApiResponses({@ApiResponse(code = 500, message = "系统出现异常", response = ErrorEntity.class)})
    @RequestMapping(value = REQUEST_MODEL + "/ExportHeader", method = RequestMethod.POST)
    public void exportLotInvReport(
            @RequestBody CountHeaderRequest search,
            HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws Exception{
        try {
            invCountService.exportCountHeader(search,servletRequest,servletResponse);
            //lotInvReportService.exportSaleInvReport(search,servletRequest,servletResponse);
        } catch (Exception e) {
            servletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            throw e;
        }
    }

/*
    @ApiOperation(value = "导出测试", notes = "导出盘点单主档")
    @ApiResponses({@ApiResponse(code = 500, message = "系统出现异常", response = ErrorEntity.class)})
    @RequestMapping(value = REQUEST_MODEL + "/testetse", method = RequestMethod.GET)
    public void testPPP(
            CountHeaderRequest search,
            HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws Exception{
        try {
            invCountService.testEsport(search,servletRequest,servletResponse);
            //lotInvReportService.exportSaleInvReport(search,servletRequest,servletResponse);
        } catch (Exception e) {
            servletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            throw e;
        }
    }
*/

    @ApiOperation(value = "查询盘点范围（分页）", notes = "查询盘点范围（分页）")
    @ApiResponses({@ApiResponse(code = 500, message = "系统出现异常", response = ErrorEntity.class)})
    @RequestMapping(value = REQUEST_MODEL + "/searchScope", method = RequestMethod.GET)
    public PagerInfo<List<InvCountScope>> searchScope(
            BigDecimal headerId, Pager<?> pager,
            HttpServletRequest servletRequest, HttpServletResponse servletResponse) {
        return invCountService.searchCountScope(headerId,pager);
    }

    @ApiOperation(value = "编辑盘点主档前查询信息", notes = "编辑盘点主档前查询信息")
    @ApiResponses({@ApiResponse(code = 500, message = "系统出现异常", response = ErrorEntity.class)})
    @RequestMapping(value = REQUEST_MODEL + "/update/headerInfo", method = RequestMethod.GET)
    public CountHeaderInsertDto searchHeaderInfo(
            BigDecimal headerId, Pager<?> pager,
            HttpServletRequest servletRequest, HttpServletResponse servletResponse) {
        return invCountService.searchHeaderDto(headerId);
    }

    @ApiOperation(value = "保存盘点主档", notes = "保存盘点主档")
    @ApiResponses({@ApiResponse(code = 500, message = "系统出现异常", response = ErrorEntity.class)})
    @RequestMapping(value = REQUEST_MODEL + "/saveHeader", method = RequestMethod.POST)
    public CountHeaderInsertDto saveHeader(
            @RequestBody CountHeaderInsertDto dto,
            HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws Exception{
        try {
            return invCountService.saveCountHeader(dto,servletRequest);
        } catch (Exception e) {
            servletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            throw e;
        }
    }

    @ApiOperation(value = "库区下拉框【传仓库】", notes = "库区下拉框【传仓库】")
    @ApiResponses({@ApiResponse(code = 500, message = "系统出现异常", response = ErrorEntity.class)})
    @RequestMapping(value = REQUEST_MODEL + "/searchZone", method = RequestMethod.POST)
    public PagerInfo<List<Zone>> searchZone(
            @RequestBody CountScopeDto dto,
            HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws Exception{
        try {
            return invCountService.searchCountZone(dto, dto.getPager());
            //lotInvReportService.exportSaleInvReport(search,servletRequest,servletResponse);
        } catch (Exception e) {
            servletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            throw e;
        }
    }

    @ApiOperation(value = "库位下拉框【传仓库&库区】", notes = "库位下拉框【传仓库&库区】")
    @ApiResponses({@ApiResponse(code = 500, message = "系统出现异常", response = ErrorEntity.class)})
    @RequestMapping(value = REQUEST_MODEL + "/searchLoc", method = RequestMethod.POST)
    public PagerInfo<List<Location>> searchLoc(
            @RequestBody CountScopeDto dto,
            HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws Exception{
        try {
            return invCountService.searchCountLoc(dto, dto.getPager());
            //lotInvReportService.exportSaleInvReport(search,servletRequest,servletResponse);
        } catch (Exception e) {
            servletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            throw e;
        }
    }

    @ApiOperation(value = "批次号下拉框【传仓库&库区&库位】", notes = "批次号下拉框【传仓库&库区&库位】")
    @ApiResponses({@ApiResponse(code = 500, message = "系统出现异常", response = ErrorEntity.class)})
    @RequestMapping(value = REQUEST_MODEL + "/searchLotno", method = RequestMethod.POST)
    public PagerInfo<List<Lotno>> searchLotno(
            @RequestBody CountScopeDto dto,
            HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws Exception{
        try {
            return invCountService.searchCountLotno(dto, dto.getPager());
            //lotInvReportService.exportSaleInvReport(search,servletRequest,servletResponse);
        } catch (Exception e) {
            servletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            throw e;
        }
    }

    @ApiOperation(value = "物料分类下拉框【传仓库&库区&库位&批次】", notes = "物料分类下拉框【传仓库&库区&库位&批次】")
    @ApiResponses({@ApiResponse(code = 500, message = "系统出现异常", response = ErrorEntity.class)})
    @RequestMapping(value = REQUEST_MODEL + "/searchCate", method = RequestMethod.POST)
    public PagerInfo<List<SkuCate>> searchCate(
            @RequestBody CountScopeDto dto,
            HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws Exception{
        try {
            return invCountService.searchCountSkuCate(dto, dto.getPager());
            //lotInvReportService.exportSaleInvReport(search,servletRequest,servletResponse);
        } catch (Exception e) {
            servletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            throw e;
        }
    }

    @ApiOperation(value = "物料下拉框【传仓库&库区&库位&批次&分类】", notes = "物料下拉框【传仓库&库区&库位&批次&分类】")
    @ApiResponses({@ApiResponse(code = 500, message = "系统出现异常", response = ErrorEntity.class)})
    @RequestMapping(value = REQUEST_MODEL + "/searchSku", method = RequestMethod.POST)
    public PagerInfo<List<Sku>> searchSku(
            @RequestBody CountScopeDto dto,
            HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws Exception{
        try {
            return invCountService.searchCountSku(dto, dto.getPager());
            //lotInvReportService.exportSaleInvReport(search,servletRequest,servletResponse);
        } catch (Exception e) {
            servletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            throw e;
        }
    }

    @ApiOperation(value = "物料导入【传仓库&库区&库位&批次&分类】", notes = "物料导入【传仓库&库区&库位&批次&分类】")
    @ApiResponses({@ApiResponse(code = 500, message = "系统出现异常", response = ErrorEntity.class)})
    @RequestMapping(value = REQUEST_MODEL + "/exportSku", method = RequestMethod.POST)
    public List<Sku> exportSku(
            @RequestParam("file") MultipartFile file,String dtoJson,
            HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws Exception{
        try {
            CountScopeDto dto=new CountScopeDto();
            //转换转义字符  不要乱动=。=
            try {
                System.out.println(dtoJson);
                dtoJson=dtoJson.replaceAll("%7B","{ ")
                        .replaceAll("%22","\"").replaceAll("%7D","}");
                Gson gson=new Gson();
                dto= gson.fromJson(dtoJson, CountScopeDto.class);
            }catch (Exception e){
                Shift.fatal("---转换JSON失败---");
            }
            return invCountService.exortSku(dto, file);
            //lotInvReportService.exportSaleInvReport(search,servletRequest,servletResponse);
        } catch (Exception e) {
            servletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            throw e;
        }
    }

    @ApiOperation(value = "编辑盘点范围前查询信息", notes = "编辑盘点范围前查询信息")
    @ApiResponses({@ApiResponse(code = 500, message = "系统出现异常", response = ErrorEntity.class)})
    @RequestMapping(value = REQUEST_MODEL + "/before/scope/{countScopeId}", method = RequestMethod.POST)
    public CountScopeInfoDto searchBeforeScope(
            @PathVariable("countScopeId") BigDecimal countScopeId,
            HttpServletRequest servletRequest, HttpServletResponse servletResponse) {
        return invCountService.searchUpdateScope(countScopeId);
    }


    @ApiOperation(value = "保存盘点范围", notes = "保存盘点范围")
    @ApiResponses({@ApiResponse(code = 500, message = "系统出现异常", response = ErrorEntity.class)})
    @RequestMapping(value = REQUEST_MODEL + "/saveScope", method = RequestMethod.POST)
    public Result<String> saveCountScope(
            @RequestBody CountScopeDto dto,
            HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws Exception{
        try {
            return invCountService.saveCountScope(dto,servletRequest);
        } catch (Exception e) {
            servletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            throw e;
        }
    }

    @ApiOperation(value = "删除盘点范围", notes = "删除盘点范围")
    @ApiResponses({@ApiResponse(code = 500, message = "系统出现异常", response = ErrorEntity.class)})
    @RequestMapping(value = REQUEST_MODEL + "/delectScope/{scopeId}/{headerId}", method = RequestMethod.POST)
    public Result<String> deleteScope(
            @PathVariable("scopeId") BigDecimal scopeId,@PathVariable("headerId") BigDecimal headerId,
            HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws Exception{
        try {
            return invCountService.deleteScope( scopeId, headerId);
        } catch (Exception e) {
            servletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            throw e;
        }
    }

    @ApiOperation(value = "生成盘点任务", notes = "生成盘点任务")
    @ApiResponses({@ApiResponse(code = 500, message = "系统出现异常", response = ErrorEntity.class)})
    @RequestMapping(value = REQUEST_MODEL + "/create/task", method = RequestMethod.POST)
    public Result<String> createCountTask(
            @RequestBody List<BigDecimal> headerIdList,
            HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws Exception{
        try {
            List<InvCountHeader> headerList = invCountHeaderMapper.
                    selectList(new QueryWrapper<InvCountHeader>().in("INV_COUNT_HEADER_ID", headerIdList));
            List<Integer> dynamicList = headerList.stream().map(t -> t.getDynamicInventory()).distinct().collect(Collectors.toList());
            for (Integer dynamic : dynamicList) {
                if (dynamic.equals(InvIsDynamicEnum.YES.code)){
                    Shift.fatal("动态库存无法生成盘点任务!");
                }
            }
            return taskService.createCountTask(headerIdList,servletRequest);
        } catch (Exception e) {
            servletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            throw e;
        }
    }

    @ApiOperation(value = "审核", notes = "审核")
    @ApiResponses({@ApiResponse(code = 500, message = "系统出现异常", response = ErrorEntity.class)})
    @RequestMapping(value = REQUEST_MODEL + "/appr", method = RequestMethod.POST)
    public Result<String> appr(
            @RequestBody List<BigDecimal> headerIds,
            HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws Exception{
        try {
            return invCountService.appr(headerIds,servletRequest);
        } catch (Exception e) {
            servletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            throw e;
        }
    }

    @ApiOperation(value = "取消审核", notes = "取消审核")
    @ApiResponses({@ApiResponse(code = 500, message = "系统出现异常", response = ErrorEntity.class)})
    @RequestMapping(value = REQUEST_MODEL + "/cancelAppr", method = RequestMethod.POST)
    public Result<String> cancelAppr(
            @RequestBody List<BigDecimal> headerIds,
            HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws Exception{
        try {
            return invCountService.cancelAppr(headerIds,servletRequest);
        } catch (Exception e) {
            servletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            throw e;
        }
    }

    @ApiOperation(value = "废弃", notes = "废弃")
    @ApiResponses({@ApiResponse(code = 500, message = "系统出现异常", response = ErrorEntity.class)})
    @RequestMapping(value = REQUEST_MODEL + "/remove", method = RequestMethod.POST)
    public Result<String> remove(
            @RequestBody List<BigDecimal> headerIds,
            HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws Exception{
        try {
            return invCountService.cancel(headerIds,servletRequest);
        } catch (Exception e) {
            servletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            throw e;
        }
    }

    @ApiOperation(value = "关单", notes = "关单")
    @ApiResponses({@ApiResponse(code = 500, message = "系统出现异常", response = ErrorEntity.class)})
    @RequestMapping(value = REQUEST_MODEL + "/close", method = RequestMethod.POST)
    public Result<String> closeHeader(
            @RequestBody List<BigDecimal> headerIds,
            HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws Exception{
        try {
            return invCountService.closeHeader  (headerIds,servletRequest);
        } catch (Exception e) {
            servletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            throw e;
        }
    }

    @ApiOperation(value = "结果送审", notes = "结果送审")
    @ApiResponses({@ApiResponse(code = 500, message = "系统出现异常", response = ErrorEntity.class)})
    @RequestMapping(value = REQUEST_MODEL + "/sendApr", method = RequestMethod.POST)
    public Result<String> sendApr(
            @RequestBody List<BigDecimal> headerIds,
            HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws Exception{
        try {
            return invCountService.sendApr  (headerIds,servletRequest);
        } catch (Exception e) {
            servletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            throw e;
        }
    }


}
